import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;

class Request{
  static const String baseUrl = "http://39.107.246.135:1224";
  static const int timeoutSeconds = 10;

  static Future<Map<String, dynamic>> postRequest({
    required String path,
    Map<String, dynamic>? body,
    Map<String,String>? header,
  })
  async {
    try {
      final url = Uri.parse('$baseUrl$path');
      // print('请求地址：$url'); // 调试日志

      final response = await http
          .post(
        url,
        body: jsonEncode(body),
        headers: {'Content-Type': 'application/json; charset=utf-8',...?header},
      )
          .timeout(
        const Duration(seconds: timeoutSeconds),
        onTimeout: () => throw TimeoutException('请求超时'),
      );

      // print('响应状态码：${response.statusCode}'); // 调试日志
      final responseBody = utf8.decode(response.bodyBytes);
      // print('响应内容：$responseBody'); // 调试日志

      return jsonDecode(responseBody);
    }  on Exception catch (e) {
      return _handleHttpExceptions(e) ;
    }
  }

  static Future<Map<String, dynamic>> patchRequest({
    required String path,
    Map<String, dynamic>? body,
    Map<String, dynamic>? queryParams,
    Map<String,String>? header,
  })
  async {
    try {
      var url = Uri.parse('$baseUrl$path');
      if(queryParams != null){
        url=url.replace(queryParameters: queryParams);
      }
      // print('请求地址：$url'); // 调试日志

      final response = await http
          .patch(
        url,
        body: body != null ? jsonEncode(body) : null, // 确保 body 不为 null
        headers: {...?header},
      )
          .timeout(
        const Duration(seconds: timeoutSeconds),
        onTimeout: () => throw TimeoutException('请求超时'),
      );

      // print('响应状态码：${response.statusCode}'); // 调试日志
      final responseBody = utf8.decode(response.bodyBytes);
      if (kDebugMode) {
        print('响应内容：$responseBody');
      } // 调试日志
      return jsonDecode(responseBody);
    }  on Exception catch (e) {
      return _handleHttpExceptions(e) ;
    }
  }

  static Future<Map<String, dynamic>> getRequest({
    required String path,
    Map<String,String>? header,
    Map<String,dynamic>? queryParams,
  })
  async {
    try {
      final url = Uri.parse('$baseUrl$path');
      if(queryParams != null){
        url.replace(queryParameters: queryParams);
      }
      // if (kDebugMode) {
      //   print('请求地址：$url');
      // } // 调试日志

      final response = await http
          .get(
        url,
        headers: {'Content-Type': 'application/json; charset=utf-8',...?header},
      )
          .timeout(
        const Duration(seconds: timeoutSeconds),
        onTimeout: () => throw TimeoutException('请求超时'),
      );

      // print('响应状态码：${response.statusCode}'); // 调试日志
      final responseBody = utf8.decode(response.bodyBytes);
      // if (kDebugMode) {
      //   print('get响应内容：$responseBody');
      // } // 调试日志

      return jsonDecode(responseBody);
    } on Exception catch (e) {
      return _handleHttpExceptions(e) ;
    }
  }

// 新增PUT请求方法
  static Future<Map<String, dynamic>> putRequest({
    required String path,
    Map<String, dynamic>? body,
    Map<String, String>? headers,
  })
  async {
    try {
      final url = Uri.parse('$baseUrl$path');
      final response = await http.put(
        url,
        body: jsonEncode(body),
        headers: {
          'Content-Type': 'application/json; charset=utf-8',
          ...?headers,
        },
      ).timeout(
        const Duration(seconds: timeoutSeconds),
        onTimeout: () => throw TimeoutException('请求超时'),
      );

      final responseBody = utf8.decode(response.bodyBytes);
      if (kDebugMode) print('PUT响应：$responseBody');

      return jsonDecode(responseBody);
    } on Exception catch (e) {
      // 统一异常处理（复用现有错误处理逻辑）
      return _handleHttpExceptions(e);
    }
  }

// 异常处理方法
  static Map<String, dynamic> _handleHttpExceptions(Exception e) {
    if (e is SocketException) {
      return _errorResponse('网络连接异常，请检查网络');
    } else if (e is TimeoutException) {
      return _errorResponse('请求超时，请稍后重试');
    } else if (e is HttpException) {
      return _errorResponse('HTTP协议异常');
    } else {
      return _errorResponse('未知错误：${e.toString()}');
    }
  }
// 异常响应
  static Map<String, dynamic> _errorResponse(String message) {
    return {
      "code": -1,
      "message": message,
      "timestamp": DateTime.now().toIso8601String(),
    };
  }

}